import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class SettingsService {
  static Database? _db;
  
  static Future<void> init() async {
    if (_db != null) return;

    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'settings.db');
    
    _db = await openDatabase(
      path,
      version: 1,
      singleInstance: false,  // 允许多个实例
      onCreate: (db, version) async {
        // 创建设置表，将 value 改为 INTEGER 类型
        await db.execute('''
          CREATE TABLE settings (
            key TEXT PRIMARY KEY,
            value INTEGER NOT NULL
          )
        ''');
        
        // 插入默认值
        await db.insert(
          'settings',
          {'key': 'exam_mode', 'value': 0},  // 0 表示做题模式
        );
        await db.insert(
          'settings',
          {'key': 'question_count', 'value': 10},
        );
      },
    );
  }

  // 保存做题模式（0: 做题模式，1: 背题模式）
  static Future<void> saveExamMode(int mode) async {
    await _db?.insert(
      'settings',
      {'key': 'exam_mode', 'value': mode},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // 保存题目数量
  static Future<void> saveQuestionCount(int count) async {
    await _db?.insert(
      'settings',
      {'key': 'question_count', 'value': count},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // 获取做题模式
  static Future<int> getExamMode() async {
    final result = await _db?.query(
      'settings',
      where: 'key = ?',
      whereArgs: ['exam_mode'],
    );
    return (result?.firstOrNull?['value'] as int?) ?? 0;  // 直接返回 int
  }

  // 获取题目数量
  static Future<int> getQuestionCount() async {
    final result = await _db?.query(
      'settings',
      where: 'key = ?',
      whereArgs: ['question_count'],
    );
    return (result?.firstOrNull?['value'] as int?) ?? 10;  // 直接返回 int
  }
}